package com.qk.filter;

import com.qk.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        //1.获取登录请求
            String uri=request.getRequestURI();
        //2.判断是否为登录请求,若是，则放行
            if(uri.contains("/login")){
                filterChain.doFilter(request,response);
                return;
            }
        //3.若不是，则获取请求头token
            String jwt= request.getHeader("token");
        //4.判断token是否为空,若是，401
            if(jwt==null ||"".equals(jwt)){
                response.setStatus(401);
                return;
            }
        //5.不为空则解析token
        try{
        JwtUtils.parseToken(jwt);
        }catch (Exception e){
            response.setStatus(401);
            return;
        }

        //6.若解析不成功，401；若成功，则放行
            filterChain.doFilter(request,response);


    }
}
